package firbi.base;

import java.util.ArrayList;
import java.util.HashMap;

import firbi.base.com.FirbiCom;

import android.app.ListActivity;
import android.content.ContentResolver;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;


public class ContactsView extends ListActivity {
	
	private ArrayList<HashMap<String,String>> mList = new ArrayList<HashMap<String,String>>();
	private String[] mIds = {};
	
	public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.contacts);
        
        mList.clear();
        addAllContacts();
        refreshContactsList();
	}
	
	public void addAllContacts() {
		ContentResolver cr = getContentResolver();
		String[] columns = {"display_name", "_id"};
		Cursor contacts_cursor = cr.query(android.provider.Contacts.People.CONTENT_URI, columns, "", null, "");
		
		Uri methodsUri = Uri.withAppendedPath(android.provider.Contacts.CONTENT_URI , android.provider.Contacts.People.ContactMethods.CONTENT_DIRECTORY);
		contacts_cursor.moveToFirst();
		mIds = new String[contacts_cursor.getCount()];
		for(int i = 0; i < contacts_cursor.getCount(); i++){
			String name = contacts_cursor.getString(0);
			String id = contacts_cursor.getString(1);
			mIds[i] = id;
			String[] cols = {"person"};
			
			Cursor address_cursor = cr.query(methodsUri, cols, "contact_methods.person='"+id+"' AND contact_methods.kind='"+android.provider.Contacts.KIND_POSTAL+"'", null, "");
			
			int numAddresses = address_cursor.getCount();
			addContactToList(name, numAddresses+"");
			contacts_cursor.moveToNext();
		}
	}
	
	public void addContactToList(String name, String numberOfAddresses) {
		HashMap<String,String> d = new HashMap<String,String>();
		d.put("nameCol", name);
		d.put("addressNumCol", numberOfAddresses+"");
		mList.add(d);
	}
	
	public void refreshContactsList() {
		SimpleAdapter dlist = new SimpleAdapter( 
				this, 
				mList,
				R.layout.contacts_list,
				new String[] {"nameCol", "addressNumCol"},
				new int[] {R.id.nameCol, R.id.addressNumCol});
		setListAdapter(dlist);
	}
	
}